import { createRouter, createWebHashHistory } from "vue-router";
import { loginStore } from "@/stores/loginStore.js";
import { remove_token } from "@/api/app.js";

const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login/login.vue"),
  },
  {
    path: "/index",
    name: "index",
    component: () => import("@/views/Layout/index.vue"),
    redirect: { name: "board" },
    children: [
      {
        path: "/board",
        name: "board",
        component: () => import("@/views/Board/index.vue"),
      },
    ],
  },
  {
    path: "/company",
    name: "company",
    component: () => import("@/views/Layout/index.vue"),
    children: [
      {
        path: "/companyinfo",
        name: "companyinfo",
        component: () => import("@/views/Company/index.vue"),
      },
    ]
  },
  {
    path: "/check",
    name: "check",
    component: () => import("@/views/Layout/index.vue"),
    children: [
      {
        path: "/checklist",
        name: "checklist",
        component: () => import("@/views/Checklist/index.vue"),
      },
    ]
  },
  {
    path: "/systemAdmin",
    name: "systemAdmin",
    component: () => import("@/views/Layout/index.vue"),
    children: [
      {
        path: "/userAdmin",
        name: "userAdmin",
        component: () => import("@/views/SystemAdmin/useradmin.vue"),
      },
      {
        path: "/hazard",
        name: "hazard",
        component: () => import("@/views/Hazard/index.vue"),
      }
    ],
  },
];
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取登录状态存储实例
  const store = loginStore();

  // 如果目标路由是登录页面，则退出登录状态
  if (to.path === "/login") {
    // 清除cookie中的token
    remove_token();
    // 清除store中的token和login_name
    store.token = "";
    store.login_name = "";
    store.isLogin = false;
    // 继续导航到目标路由
    next();
  } else {
    // 判断用户是否已登录，继续导航到目标路由，否则导航到登录页面
    store.isLogin ? next() : next("/login");
  }
});

export default router;
